<template>
  <div class="">
    <van-nav-bar
      @click-left="goBack"
      left-arrow
      :title="$route.query.id ? $route.query.title + '视频' : '创建视频'"
      fixed
    ></van-nav-bar>
    <main>
      <input
        type="text"
        placeholder="请输入视频标题20字以内"
        v-model.trim="title"
        maxlength="30"
      />
      <!-- <textarea placeholder="请输入视频标题20字以内"></textarea> -->
      <van-field
        v-model.trim="describes"
        class="textarea"
        rows="3"
        autosize
        type="textarea"
        maxlength="300"
        placeholder="请输入视频描述300字以内"
      />

      <h3>视频上传</h3>
      <div class="box">
        <div class="u_video">
          <div class="box">
            <img
              src="../../assets/images/marketing/add_video.png"
              alt=""
              v-if="videoUrl == ''"
            />

            <!-- <video
              class="video_show"
              ref="videos"
              :src="videoUrl"
              v-if="videoUrl !=''"
              @click="playPause($event)"
            ></video> -->
            <img
              v-if="videoUrl != ''"
              src="../../assets/images/marketing/video_finish.png"
              alt=""
            />
            <input
              class="video_file"
              name="file"
              type="file"
              accept="video/*"
              @change="changeVideo($event)"
              v-if="videoUrl == ''"
              id="fileName"
            />
            <div
              class="video_close"
              @click="videoCloseFn"
              v-if="videoUrl != ''"
            ></div>
          </div>
        </div>

        <!-- 封面 -->
        <div class="upload" style="margin-left: 20px">
          <img
            class="clickUp"
            src="../../assets/images/marketing/add_videoCover.png"
            @click="clickUp(2)"
            v-if="cover == ''"
          />
          <img
            v-else
            @click="clickUp(2)"
            class="clickUp"
            :src="$publicObj.urlImg(cover)"
            alt=""
          />
        </div>
      </div>
      <div id="editors"></div>

      <input
        name="file"
        type="file"
        ref="coverfile"
        accept="image/*"
        style="display: none"
        @change="onUpload(2)"
      />
    </main>
    <footer>
      <div class="next" @click="next">下一步</div>
    </footer>
    <!-- 弹框 -->
    <van-dialog v-model="show" :show-confirm-button="false">
      <template #title>
        <van-icon name="cross" @click="show = false" />
      </template>
      <template #default>
        <div class="cont">
          <p v-if="isPay == 2">当前账号余额不足无法发布！</p>
          <p v-else-if="isPay == 1">您还未设置支付密码！</p>
          <p v-else-if="isPay == 3">当前未绑定公众号！</p>
          <van-divider />
          <div class="foot" @click="go(2)" v-if="isPay == 2">去充值</div>
          <div class="foot" @click="go(1)" v-else-if="isPay == 1">去设置</div>
          <div class="foot" @click="go(3)" v-else-if="isPay == 3">去绑定</div>
        </div>
      </template>
    </van-dialog>
    <!-- 弹出密码输入 -->
    <van-popup
      v-model="showPopup"
      position="bottom"
      :style="{ height: '60%', 'padding-top': '20px' }"
    >
      <!-- 密码输入框 -->
      <van-password-input
        :value="pwd"
        info="密码为 6 位数字"
        :focused="showKeyboard"
        @focus="showKeyboard = true"
      />
      <!-- 数字键盘 -->
      <van-number-keyboard
        v-model="pwd"
        :show="showKeyboard"
        @blur="showKeyboard = false"
      />
    </van-popup>
  </div>
</template>

<script>
import wangeditor from "wangeditor";
export default {
  name: "",
  data() {
    return {
      title: "", //标题
      describes: "", //描述
      editor: "",
      editorContent: "", //视频说明
      cover: "", //封面图片地址
      videoUrl: "", //视频图片
      form: false, //是否添加表单
      attention: false, //是否关注公众号
      changeTitle: false, //是否可更改标题
      card: false, //是否允许添加名片
      isSpread: 1, //是否推广
      totalSpread: 0, //是否全网付费推广
      spreadPrice: "", //单价
      spreadNum: "", //推广数
      show: false, //弹框
      showPopup: false, //密码弹出
      pwd: "", //密码
      showKeyboard: true,
      isPay: 1, //是去充值还是去支付
      vidoShow: false, //上传的显示隐藏
      beforeBalance: 0, //原推广总价
      beforePrice: "", //原推广单价
      beforeNum: "", //原推广次数
    };
  },

  //生命周期 - 创建完成（访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.$store.dispatch("updateUserInfo");
    this.seteditor();
    document.querySelector("#app").style.backgroundColor = "#fff";
    //如果时充值完或设置完支付密码
    if (JSON.parse(sessionStorage.getItem("articleInfo"))) {
      this.echoInfo();
    } else {
      if (this.$route.query.id) {
        this.getVideoInfo();
      }
    }
  },
  destroyed() {
    window.removeEventListener("popstate", this.backChange, false);
  },
  methods: {
    // 手机系统返回键事件
    backChange() {
      if (JSON.parse(sessionStorage.getItem("articleInfo"))) {
        sessionStorage.removeItem("articleInfo");
      }
    },
    //点击下一步
    next() {
      let {
        title,
        describes,
        editorContent: explains, //视频说明
        videoUrl: url, //视频图片
        cover,
        isSpread,
        spreadPrice,
        spreadNum,
        form,
        attention,
        spreadTotalPrice,
        card, //是否名片
        changeTitle, //是否可更改标题
        totalSpread, //是否全网付费推广
        beforeBalance, // 原推广总价
        beforePrice, //原推广单价
        beforeNum, // 原推广次数
      } = this;
      if (title.trim() == "") return this.$toast("请输入视频标题!");
      if (describes.trim() == "") return this.$toast("请输入视频描述!");
      if (url.trim() == "") return this.$toast("请上传视频!");
      if (cover.trim() == "") return this.$toast("请输入视频封面!");
      let obj = {
        title, //标题
        describes, //描述
        explains, //说明
        url, //视频
        cover, //封面
        isSpread, //是否推广
        spreadPrice, //单价
        spreadNum, //次数
        spreadTotalPrice, //总价
        form, //是否表单
        attention, //是否关注
        card, //是否名片
        changeTitle, //是否可更改标题
        totalSpread, //是否全网付费推广
        beforeBalance, // 原推广总价
        beforePrice, //原推广单价
        beforeNum, // 原推广次数
      };
      sessionStorage.setItem("articleInfo", JSON.stringify(obj));
      if (this.$route.query.id) {
        this.$router.push(
          `/addVideoNext?id=${this.$route.query.id}&title=${this.$route.query.title}`
        );
      } else {
        this.$router.push("/addVideoNext");
      }
    },
    //视频上传
    clickUp(n) {
      if (n == 1) {
        this.$refs.videofile.click();
      } else {
        this.$refs.coverfile.click();
      }
    },
    //   上传文件
    onUpload(n) {
      this.$publicObj.getLoading("上传中...");
      let _this = this;
      let file;
      if (n == 1) {
        file = this.$refs.videofile.files[0];
      } else {
        file = this.$refs.coverfile.files[0];
      }
      _this.nowFile = file;
      // 上传
      _this.$publicObj.uploadFile(
        file,
        function(imgData) {
          if (n == 1) {
            _this.videoUrl = imgData;
          } else {
            _this.cover = imgData;
          }
          _this.$toast("上传成功");
          _this.$publicObj.closeLoading();
        },
        "/sys/oss/upload"
      );
    },

    // 操作视频
    changeVideo(e) {
      let _this = this;
      let video_file = e.target.files[0];
      let type = video_file.type; // 文件类型
      let fileurl = URL.createObjectURL(video_file); // 文件路径

      let audioElement = new Audio(fileurl); // audio可获取视频的时长
      // audioElement.addEventListener("loadedmetadata", function (_event) {
      let duration = Math.floor(audioElement.duration); // 视频时长
      let video_pow = video_file.size / Math.pow(1024, 2); // 视频大小转化字节
      let video_size = Math.floor(video_pow * 10) / 10; // 视频大小字节转化为M
      if (duration < 0) {
        _this.$toast("请检查视频格式");
        return false;
      }
      if (video_size > 100) {
        _this.$toast("视频不能大于100MB");
        return false;
      }
      // });
      if (fileurl) {
        _this.getAddVideo(video_file, fileurl);
      } else {
        _this.vidoShow = false;
      }
    },
    //上传视频
    async getAddVideo(files, fileurl) {
      let _this = this;
      this.$publicObj.getLoading();
      _this.$publicObj.uploadFile(
        files,
        function(imgData) {
          _this.videoUrl = imgData;
          _this.$toast("上传成功");
          _this.$publicObj.closeLoading();
          _this.vidoShow = true;
        },
        "/sys/oss/upload"
      );
    },
    //播放视频
    playPause(e) {
      e.target.paused ? e.target.play() : e.target.pause();
    },
    // 关闭视频
    videoCloseFn() {
      this.vidoShow = false;
      this.videoUrl = "";
    },
    // 回显数据
    echoInfo() {
      let info = JSON.parse(sessionStorage.getItem("articleInfo"));
      this.title = info.title; //标题
      this.describes = info.describes; //描述
      this.editor.txt.html(info.explains); //说明
      this.cover = info.cover; //封面图
      this.videoUrl = info.url; //视频图片
      this.isSpread = info.isSpread; //是否推广
      this.spreadPrice = info.spreadPrice; //单价
      this.spreadNum = info.spreadNum; //推广数
      this.form = info.form; //是否添加表单
      this.attention = info.attention; //是否关注公众号
      this.changeTitle = info.changeTitle; //是否可更改标题
      this.card = info.card; //是否允许添加名片
      this.totalSpread = info.totalSpread || 0; //是否全网付费推广
      this.beforeBalance = info.beforeBalance; //原推广总价
      this.beforePrice = info.spreadPrice; //原推广单价
      this.beforeNum = info.spreadNum; //原推广次数
    },
    //返回清空数据
    goBack() {
      if (JSON.parse(sessionStorage.getItem("articleInfo"))) {
        sessionStorage.removeItem("articleInfo");
      }
      this.$router.back();
    },
    //获取视频数据
    async getVideoInfo() {
      let userInfo = JSON.parse(sessionStorage.getItem("userWxData"));
      let {
        openid,
        nickname: name,
        headimgurl: image,
        sex,
        city,
        province,
      } = userInfo;
      this.tableId = Number(this.$route.query.id);
      let obj = {
        tableId: this.$route.query.id,
        openId: openid,
        name,
        image,
        sex,
        city,
        province,
        userId: this.$store.state.userInfo.account,
        tableType: 4,
      };
      let res = await this.$api.getArticleInfo(obj);
      if (res.code != 0) return;
      this.title = res.data.title; //标题
      this.describes = res.data.describes; //描述
      this.editor.txt.html(res.data.explains); //说明

      this.cover = res.data.cover; //封面图
      this.videoUrl = res.data.url; //视频图片
      this.isSpread = res.data.isSpread; //是否推广
      this.spreadPrice = res.data.spreadPrice; //单价
      this.spreadNum = res.data.spreadNum; //推广数
      this.form = res.data.form; //是否添加表单
      this.attention = res.data.attention; //是否关注公众号
      this.changeTitle = res.data.changeTitle; //是否可更改标题
      this.card = res.data.card; //是否允许添加名片
      this.totalSpread = res.data.totalSpread || 0; //是否全网付费推广
      this.beforeBalance = res.data.spreadTotalPrice; //原推广总价
      this.beforePrice = res.data.spreadPrice; //原推广单价
      this.beforeNum = res.data.spreadNum; //原推广次数
    },
    //文本编辑器
    seteditor() {
      this.editor = new wangeditor("#editors");
      //editor改变时，将里面的内容放进editorContent
      this.editor.config.onchange = (html) => {
        // console.log(html);
        this.editorContent = html;
      };

      // 配置菜单栏，设置不需要的菜单
      this.editor.config.excludeMenus = [
        "emoticon",
        "video",
        "code",
        "table",
        "todo",
      ];
      this.editor.config.placeholder = "请输入视频说明";
      //   /关闭粘贴样式的过滤
      this.editor.config.pasteFilterStyle = false;
      //忽略粘贴内容中的图片
      this.editor.config.pasteIgnoreImg = true;
      // 使用 base64 保存图片
      this.editor.config.uploadImgShowBase64 = true;
      // 隐藏“网络图片”tab
      this.editor.config.showLinkImg = false;
      //改变z-index
      this.editor.config.zIndex = 10;
      // 最大300M
      this.editor.config.uploadImgMaxSize = 300 * 1024 * 1024;
      this.editor.config.uploadImgServer =
        "http://wx-001.unionnetwork.com/zk/sys/oss/upload";
      this.editor.config.customUploadImg = (files, insert) => {
        // files 是 input 中选中的文件列表
        // insert 是获取图片 url 后，插入到编辑器的方法
        // console.log(files);
        let _this = this;
        let file = files[0];
        _this.$publicObj.getLoading("上传中...");
        // 上传代码返回结果之后，将图片插入到编辑器中
        _this.$publicObj.uploadFile(
          file,
          function(imgData) {
            insert(imgData);
            _this.$toast("上传成功");
            _this.$publicObj.closeLoading();
          },
          "/sys/oss/upload"
        );
      };

      this.editor.create();
    },
  },
};
</script>
<style scoped lang="less">
/* @import url(); 引入css类 */
/deep/ .van-dialog__header {
  text-align: right;
  padding: 15px 15px 0 0;
}
// 进入前和结束后的状态
.v-enter,
.v-leave-to {
  opacity: 0;
}
// 进入和离开的动画时间段
.v-enter-active,
.v-leave-active {
  transition: all 0.5s ease;
}
.van-dialog {
  width: 272px;
}
.van-cell__value {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .van-field {
    width: 80px;
    margin-right: 5px;
  }
}
#editors {
  margin-top: 18px;
}
.cont {
  font-size: 14px;
  font-weight: 700;
  color: #353535;
  text-align: center;
  p {
    padding: 20px 0;
  }
  .van-divider {
    margin: 0;
  }
  .foot {
    width: 100%;
    height: 43px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #009dff;
  }
}
main {
  height: calc(100vh - 127px);
  padding: 46px 15px 0;
  overflow-y: scroll;
  input {
    margin-top: 7px;
    height: 40px;
    width: 100%;
    opacity: 1;
    background: #f3f5f7;
    border-radius: 5px;
    border: none;
    font-size: 12px;
    padding-left: 12px;
    box-sizing: border-box;
    &::-webkit-input-placeholder {
      /* placeholder颜色  */
      color: #bebebe;
    }
  }

  .textarea {
    margin-top: 10px;
    background-color: #f3f5f7;
    padding: 12px !important;
    border-radius: 5px;
  }
  .box {
    display: flex;

    .upload {
      width: 99px;
      height: 99px;
      img {
        width: 100%;
        height: 100%;
        margin-bottom: 14px;
      }
    }
    //视频
    .u_video {
      width: 99px;
      height: 99px;
      position: relative;
      background-color: #fff;
      .box {
        width: 100%;
        height: 100%;
        display: -webkit-flex;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-wrap: wrap;
        img {
          width: 100%;
          height: 100%;
        }

        video {
          width: 100%;
          height: 100%;
        }
        input {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          z-index: 22;
          opacity: 0;
        }
        .video_close {
          cursor: pointer;
          position: absolute;
          top: 0;
          right: 0;
          z-index: 10;
          width: 15px;
          height: 15px;
          background: url("../../assets/w_shanchu.png") right center / 100% 100%
            no-repeat;
          background-color: rgba(0, 0, 0, 0.7);
          border-radius: 0 0 0 12px;
        }
      }
    }
  }
  .up {
    margin-top: 10px;
    .uploading {
      width: 80px;
      height: 80px;
      position: relative;
      background-color: #fff;
    }
    //封面
    .u_img {
      width: 80px;
      height: 80px;
      box-sizing: border-box;
      margin-top: 4.000008px;
      box-shadow: 3.5px dashed rgba(153, 153, 153);
      .van_img {
        width: 80px;
        height: 80px;
        border: 0;
      }
      .poster_tips {
        width: 80px;
        height: 80px;
        display: -webkit-flex;
        display: flex;
        justify-content: center;
        align-items: center;
        img {
          width: 100%;
          height: 100%;
        }
      }
      /deep/ .van-uploader {
        .van-uploader__preview-delete {
          width: 11.71875px;
          height: 11.71875px;
          i {
            font-size: 11.71875px;
            top: -0.585938px;
            left: -0.585938px;
          }
        }
      }
    }

    .img_Show {
      position: relative;

      .close {
        position: absolute;
        width: 12px;
        height: 12px;
        left: 68px;
        color: #fff;
        background-color: #000;
        border-bottom-left-radius: 10px;
        font-size: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .imgShow {
        display: flex;
        align-items: center;
        width: 80px;
        height: 80px;
        overflow: hidden;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  p {
    margin: 5px;
    font-size: 10px;
    text-align: left;
    color: #999999;
    letter-spacing: 1px;
  }
  h3 {
    margin: 15px 0;
    font-size: 14px;
    color: #333333;
    &:last-of-type {
      font-weight: 700;
      margin: 25px 0;
    }
  }
  .van-cell {
    padding: 10px 0;
  }
}
footer {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  background-color: #fff;
  .next {
    width: 321px;
    height: 41px;
    background-color: #477fe6;
    font-size: 13px;
    color: #ffffff;
    border-radius: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
